<?php
/*1 выводить список тем
 *2 голосовалка
 * 
 * 
 */
include_once('../init.inc.php');

include_once ('header.php');


?>
<script>
$(document).ready(function() {   

	//$("#pollAjaxLoader").hide(); //hide the ajax loader
	//$("#pollMessage").hide(); //hide the ajax loader
	$(".like-button").click(function() {

		var pollAnswerVal = $('input:submit[name=pollAnswerID]:submit').val();//Getting the value of a selected radio element.
                var pollAnswerID = $(this).attr('id');
		if ($('input:submit[name=pollAnswerID]').length) {
			//$("#pollAjaxLoader").show(); //show the ajax loader
			$.ajax({  
				type: "POST",  
				url: "ajax.php",  
				data: { ID: pollAnswerID, pollAnswerVal: pollAnswerVal, action: "vote" },
				success: function(theResponse) { 
                                  
					//the functions.php returns a response like "1|13|#ffcc00-2|32|#00ff00-3|18|#cc0000-63" which the first number is the answerID, second is the points it has and third is the color for that answer's graph. The last number is the sum of all points for easilt calculating percentages.
				
						//$("#pollAjaxLoader").hide(); //hide the ajax loader
						//$("#pollMessage").html("sorry, you already voted.").fadeTo("slow", 1);
					
						var numberOfAnswers 		= (theResponse).split("-").length-2;//calculate the number of answers
						var splittedResponse 		= (theResponse).split("-");
						var pollAnswerTotalPoints 	= splittedResponse[numberOfAnswers+1];
	
						//for (i=0;i<=numberOfAnswers;i++)
						//{
							var splittedAnswer 		= (theResponse).split("|");
							var pollAnswerID 		= (splittedAnswer[0]);
							var pollAnswerPoints 	= (splittedAnswer[1]);
							var allPolls 	= (splittedAnswer[2]);
							//var pollPercentage		= (100 * pollAnswerPoints / pollAnswerTotalPoints);
							//$(".pollChart" + pollAnswerID).css("background-color",pollAnswerColor);
							//$(".pollChart" + pollAnswerID).animate({width:pollPercentage + "%"});
							//$("#pollAnswer" + pollAnswerID).html(" (" + Math.round(pollPercentage) + "% - " + pollAnswerPoints + " votes)");
                                                        var percentPoll = pollAnswerPoints/(allPolls/100);
                                                        $("#pollAnswer" + pollAnswerID).html(percentPoll.toFixed(1));
                                                        $("#pollall").html(allPolls);
                                                        //$("#"+pollAnswerID).removeClass();
                                                        //$("#"+pollAnswerID).addClass("like-button btn btn-danger");
                                                        $('.btn').hide();
                                                        $('.h_voted').show();                                
                                                        $('.h_voted2').hide();
							//$("#pollRadioButton" + pollAnswerID).attr("disabled", "disabled"); //disable the radio buttons
						//}
						//$("#pollAjaxLoader").hide(); //hide the ajax loader again
						//$("#pollSubmit").attr("disabled", "disabled"); //disable the submit button
					
				}  
			});  
			return false; 
	
	
		
		} else {
			$("#pollMessage").html("please select an answer.").fadeTo("slow", 1, function(){
				setTimeout(function() {
					$("#pollMessage").fadeOut("slow");
				}, 3000);																		 
			});
			return false;
		}
	
	});

});    
 </script>
 <div class="h_voted" > <h2 class="text-info">Articles for next month</h2></div>
  <div class="h_voted2" > <h2 class="text-info">Vote for new articles!</h2></div>
    
     <table class="mytable">
         <thead>
         <th class="h_voted2" style="width: 25px;"></th>
         <th class="h_voted2" style="text-align: left;"></th>
         <th class="h_voted" ></th>            
         </thead>   
 <?php
 $sql = "SELECT p.pollID, p.pollQuestion, a.pollAnswerPoints
        FROM `polls` AS p
        LEFT JOIN `pollanswers` AS a ON p.pollID = a.pollID";

 $result = mysql_query($sql) or die('Error, insert query failed');
 $totalPoll = getAllPoll();
 $progress=array("progress progress-info", "progress progress-success", "progress progress-warning", "progress progress-danger");

    $prog_count=0;
    
                while ($row = mysql_fetch_assoc($result)) { 
                     if (!isset($row['pollAnswerPoints'])) $row['pollAnswerPoints']= 0;
                    ?>
                                    <tr>
                                        <td>
                                            <!--<a id="<?php //echo $row['ID'];?>" href="#" class="addCart">Add</a>-->
                                            <form onsubmit="go()">
                                                <input id="<?php echo $row['pollID'];?>" class="like-button btn" type="submit" alt="I like this" value="Vote" name="pollAnswerID">
                                            </form>
                                            
                                        
                                        </td>
                                        
                    <?php    foreach ($row as $key=>$cellValue){ 
                                        if ($key=="pollID") continue;
                                        if ($key=="pollAnswerPoints") continue;
                                        if ($key=="pollQuestion")  {?>
                                        <td class="h_voted2" style="text-align: left;">
                                            <strong style="margin-left: 2em;">
                                              <?php 
                                              $question = excerpt($cellValue);
                                              echo $question; ?>
                                            </strong>
                                        </td>
                                         <?php }else { ?>
                                             <td>
                                           
                                              <?php echo excerpt($cellValue); ?>
                                          
                                             </td>
                                             
                                             
                                       <?php       
                                         }
                                                             
                                                                }
                                              $tek_poll = $row['pollAnswerPoints'];                                          
                                              $percent_poll = round($tek_poll/($totalPoll/100), 1) ;            
                                         ?>
                                             <td class="h_voted">
                                                 <div style="width: 400px;">
                                                 <strong> <?php echo "$question - <span id=\"pollAnswer".$row['pollID']."\" >".trim($percent_poll).'</span>%'; ?> </strong>
                                                     <div class="<?php echo "progress progress-info"; ?>">
                                                             <div class="bar" style="width: <?php echo trim($percent_poll).'%;'; ?> "></div>
                                                     </div>
                                                 </div>   
                                             </td>
                   <?php     userPoll($row['pollID']);  //скрываем голосовавших             
                                $prog_count++;
                                    if ($prog_count>=4) $prog_count=0;
                   }   
 
 
 ?>
     </table>
  <div class="alert alert-info">Общее количество проголосовавших: <span id="pollall" style="color:red"><?php echo $totalPoll; ?></span> </div>

 <?php 
 
include_once '../class/archive.php';
 
 $archive = archive::getInstance();
 
 
 
 
 
 include_once 'footer.php'; ?>
<?php
function getAllPoll()
{
  $query  = "SELECT sum(pollAnswerPoints) as sum FROM pollanswers";
	$result = mysql_query($query);
        
         

	$row = mysql_fetch_array($result, MYSQL_ASSOC);
 
    
    return $row['sum'];
    
    
}


function userPoll($ID){
    
     $usermail = mysql_real_escape_string($_SESSION['amembermail']);  
    
    if ($usermail){
        /*
    $sql = "SELECT *
        FROM `userpoll`
        WHERE pollID=$ID AND usermail='$usermail' LIMIT 1";
         
         */
    
     $sql = "SELECT *
        FROM `userpoll`
        WHERE usermail='$usermail' LIMIT 1";
    
    $result = mysql_query($sql) or die('Error, insert query failed');
    $row = mysql_fetch_assoc($result); 
    $timepoll = strtotime($row['poll_date']);
    $timenow = time();
    //сколько суток прошло с последнего голосования
    $diff = (int)(($timenow - $timepoll)/(60*60*24));
    
   // $tmp = date('Y-m-d H:i:s', $timepoll);
   // $tmp2 = date('Y-m-d H:i:s', time());
    }else exit;
    
    if ($row>0 && $diff<30){
        //уже голосовал
         // return $pollAnswerPoints;
      /*  echo "<script>
              $('#$ID').removeClass();
              $('#$ID').addClass('like-button btn btn-danger');
              </script>
                ";*/
        echo "<script>
              $('#$ID').removeClass();
              $('#$ID').hide();
              $('.h_voted').show();
              $('.h_voted2').hide();
              </script>
                ";
          return;
          /*$("#7").removeClass();
           * $("#7").addClass("btn btn-success");
           * 
           */
    }
    //еще не голосовал
    echo "<script>
              $('#$ID').removeClass();
              $('#$ID').addClass('like-button btn btn-success');
              $('.h_voted').hide();
               $('.h_voted2').show();
              </script>
                ";
          return;
}
?>